package com.bawei.module_mine.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_storage.room.entity.HistoryEntity
import com.bawei.module_mine.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class HistoryVerticalAdapter(
    private val data: MutableList<HistoryEntity>
) : RecyclerView.Adapter<HistoryVerticalAdapter.HistoryViewHolder>() {

    var onItemClick: ((HistoryEntity, Int) -> Unit)? = null
    var onItemLongClick: ((HistoryEntity, Int) -> Unit)? = null
    var onDeleteClick: ((HistoryEntity, Int) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_history_vertical, parent, false)
        return HistoryViewHolder(view)
    }

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        val item = data[position]
        holder.tvTitle.text = item.title
        holder.tvProgress.text = when {
            item.lastPosition > 0L -> "已观看至${formatTime(item.lastPosition)}"
            item.progress > 0 -> "已观看至${item.progress}%"
            else -> "未观看"
        }
        holder.tvAuthor.text = item.authorName
        Glide.with(holder.itemView.context)
            .load(item.primaryImg)
            .transform(CenterCrop(), RoundedCorners(8))
            .into(holder.ivCover)
        holder.itemView.setOnClickListener { onItemClick?.invoke(item, position) }
        holder.itemView.setOnLongClickListener {
            onItemLongClick?.invoke(item, position)
            true
        }
        holder.btnDelete.setOnClickListener { onDeleteClick?.invoke(item, position) }
    }

    fun removeAt(position: Int) {
        data.removeAt(position)
        notifyItemRemoved(position)
    }

    private fun formatTime(ms: Long): String {
        val totalSeconds = ms / 1000
        val minutes = totalSeconds / 60
        val seconds = totalSeconds % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    override fun getItemCount(): Int = data.size

    inner class HistoryViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivCover: ImageView = view.findViewById(R.id.iv_cover)
        val tvTitle: TextView = view.findViewById(R.id.tv_title)
        val tvProgress: TextView = view.findViewById(R.id.tv_progress)
        val tvAuthor: TextView = view.findViewById(R.id.tv_author)
        val btnDelete: ImageButton = view.findViewById(R.id.btn_delete)
    }
} 